//
//  HomePage_Vc.swift
//  Pods
//
//  Created by eme on 2017/3/24.
//
//


/*
 owner:cy
 update:2017年01月17日17:43:56
 info: 首页
 model: UserModel
 viewmodel: HomePage_Vm
 */
import RxSwift
import UtilCore
import MJRefresh
import RickonCore
import URLNavigator

let placeKeyWork = "请输入您想要的商品"
class HomePage_Vc: Base_Vc {
    
    /****************************Storyboard UI设置区域****************************/
    @IBOutlet weak var keyword_Lb: UILabel!
    @IBOutlet weak var topSearchBar_V: UIView!
    @IBOutlet weak var homePage_Cv: UICollectionView!
    
    @IBOutlet weak var flowLayout: UICollectionViewFlowLayout!
    var homePageItems = [IndexModel]() {
        didSet {
            self.homePage_Cv.reloadData()
        }
    }
    
    @IBOutlet var searchBar_Tap: UITapGestureRecognizer!
    /*----------------------------   自定义属性区域    ----------------------------*/
    // 顶部刷新
    let header = MJRefreshNormalHeader()
    // 底部刷新
    let footer = MJRefreshAutoNormalFooter()
    
    var manageVm:HomePage_Vm?
    /// 返回默认keyword
    var defaultKeyWord:String?{
        didSet{
            self.keyword_Lb.text = self.defaultKeyWord
        }
    }
    
    private lazy var rightBtn: UIButton = {
        let button = UIButton()
        button.frame = CGRect(x: 0, y: 0, width: 30, height: 35)
        button.setImage(UIImage(named: "xiaoxi-readed", in: RobbCore.bundle, compatibleWith: nil), for: .normal)
        return button
    }()
    private lazy var leftBtn: UIButton = {
        let button = UIButton()
        button.frame = CGRect(x: 0, y: 0, width: 30, height: 35)
        button.setImage(UIImage(named: "scanbtn", in: RobbCore.bundle, compatibleWith: nil), for: .normal)
        return button
    }()
    /****************************Storyboard 绑定方法区域****************************/
    
    
    
    /**************************** 以下是方法区域 ****************************/
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        
    }
    /**
     界面基础设置
     */
    override func setupUI() {
        self.defaultKeyWord = placeKeyWork
        NotificationCenter.default.addObserver(self, selector: #selector(HomePage_Vc.getDefaultKeyWordResult(notification:)), name: NSNotification.Name(rawValue: AppConfig.notification.defaultKeyWordKey), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(HomePage_Vc.getMessagenumResult(notification:)), name: NSNotification.Name(rawValue: AppConfig.notification.messagenumKey), object: nil)
        /**
         *  自定义 导航栏左侧 返回按钮
         */
        self.customLeftBarButtonItem()
        ///隐藏滑动条
        self.homePage_Cv.showsVerticalScrollIndicator = false
        // 下拉刷新
        header.setRefreshingTarget(self, refreshingAction: #selector(HomePage_Vc.headerRefresh))
        self.homePage_Cv.mj_header = header
        self.homePage_Cv.mj_footer = footer
        if #available(iOS 9.0, *) {
            //            self.flowLayout.sectionHeadersPinToVisibleBounds = true
        } else {
            // Fallback on earlier versions
        }
        self.searchBar_Tap
            .rx.event
            .map({ _ in
                if let defaultKeyWord = self.defaultKeyWord, defaultKeyWord != placeKeyWork {
                    return  ("searchpage",["keyWord":defaultKeyWord])
                }else{
                    return  ("searchpage",nil)
                }})
            .bindTo(self.view.rx_openUrl).addDisposableTo(disposeBag)
        self.rightBtn.rx.tap.map{("message",nil)}.bindTo(self.view.rx_openUrl).addDisposableTo(disposeBag)
        self.leftBtn.rx.tap.map{("scan",nil)}.bindTo(self.view.rx_openUrl).addDisposableTo(disposeBag)
    }
    /**
     app 主题 设置
     */
    override func setViewTheme(){
        self.homePage_Cv.backgroundColor = Theme.robb.homePage.homepage_bg
        self.topSearchBar_V.changeBorderColor(Theme.robb.homePage.searchbar_border, cornerRadius: 6.0, borderWidth: 0.5)
        self.topSearchBar_V.backgroundColor = Theme.robb.homePage.searchbar_border
        footer.stateLabel.font = UIFont(name: Theme.font.normal, size: 12)
        footer.stateLabel.textColor = UIColor(hex: "999999")
        footer.setTitle("已经到底咯", for: .noMoreData)
    }
    /**
     绑定到viewmodel 设置
     */
    override func bindToViewModel(){
        /// 这块需要注意 ，其实应该发两次请求， 一次是notification触发的就是在有网的时候， 另外一次就是HomePage_Vc 的viewWillAppear 触发的
        let refreshTriger = Observable.of(
            rx.sentMessage(#selector(HomePage_Vc.headerRefresh)).map { _ in () },
            rx.sentMessage(#selector(HomePage_Vc.viewWillAppear)).map { _ in () }.take(1),
            NotificationCenter.default.rx.notification(Notification.Name(rawValue: AppConfig.notification.netWorkSuccessKey), object: nil).map { _ in () },
            NotificationCenter.default.rx.notification(Notification.Name(rawValue: AppConfig.notification.reloginSuccessKey), object: nil).map { _ in () }
            )
            .merge()
        /// 获取进货单数量
        refreshTriger
            .subscribe(onNext: { ( _ ) in
                _ = "orderformbadge".openURL()
                _ = "defaultKeyWord".openURL()
                _ = "messagenum".openURL()
            })
            .disposed(by: disposeBag)
        //        refreshTriger.bindTo(self.updateBadgeVm!.updateSubject).addDisposableTo(disposeBag)
        
        self.manageVm = HomePage_Vm(refreshTriger: refreshTriger)
        self.manageVm?.loading.asObservable().bindTo(self.view.rx_loading).addDisposableTo(disposeBag)
        self.manageVm?.error.asObserver().bindTo(self.view.rx_error).addDisposableTo(disposeBag)
        self.manageVm?.indexElements
            .asObservable()
            //            .do(onNext: {[unowned self] (_) in
            //                self.homePage_Cv.mj_header.endRefreshing()
            //            })
            .subscribe(onNext: {[unowned self] (list) in
                self.homePageItems = list
            }).disposed(by: disposeBag)
        self.footer.endRefreshingWithNoMoreData()
    }
    /**
     自定义leftBarButtonItem
     */
    override func customLeftBarButtonItem()  {
        let  rightItem = UIBarButtonItem(customView: self.rightBtn)
        self.navigationItem.rightBarButtonItem = rightItem
        let leftItem = UIBarButtonItem(customView: self.leftBtn)
        self.navigationItem.leftBarButtonItem = leftItem
    }
    // 顶部刷新
    func headerRefresh(){
        self.homePage_Cv.mj_header.endRefreshing()
    }
    
    func footerRefresh(){
        self.homePage_Cv.mj_footer.endRefreshing()
    }
    func getDefaultKeyWordResult(notification: NSNotification) {
        if let keyword = notification.object as? String {
            self.defaultKeyWord = keyword
        }
    }
    ///取到 未读消息
    func getMessagenumResult(notification: NSNotification) {
        if let msgNum = notification.object as? Int {
            if msgNum == 0 {
                self.rightBtn.setImage(UIImage(named: "xiaoxi-readed", in: RobbCore.bundle, compatibleWith: nil), for: .normal)
            }else{
                self.rightBtn.setImage(UIImage(named: "xiaoxi-unread", in: RobbCore.bundle, compatibleWith: nil), for: .normal)
            }
        }
    }
}
// MARK: - UICollectionViewDataSource
extension HomePage_Vc:UICollectionViewDataSource{
    func numberOfSections(in collectionView: UICollectionView) -> Int{
        return self.homePageItems.count
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
        let item = self.homePageItems[section]
        return item.numberOfItemsInSection
    }
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView{
        if kind == UICollectionElementKindSectionHeader {
            let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "HomePageHeaderView", for: indexPath) as! HomePageHeaderView
            let item = self.homePageItems[indexPath.section]
            headerView.didSelected_Closure = { model in
                _ = item.headerurl.openURL()
            }
            headerView.item = item
            return headerView
        }else{
            let footerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "HomePageFooterView", for: indexPath)
            return footerView
        }
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{
        let item = self.homePageItems[indexPath.section]
        switch item.ttype {
        case "t1_1","t1_2":
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "T1_1_CCell", for: indexPath) as! T1_1_CCell
            
            cell.cpImageItem = item.t1List
            cell.content_Cpv.timeInterval = Double(item.time) ?? 5.0
            cell.didSelectItem_Closure = { item in
                _ = item.url.openURL()
            }
            return cell
        case "t1_3":
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "T1_3_CCell", for: indexPath) as! T1_3_CCell
            cell.listItem = item.t1List
            cell.didSelectItem_Closure = { item in
                _ = item.url.openURL()
            }
            return cell
        case "t1_4","t1_5":
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "T1_4_5_CCell", for: indexPath) as! T1_4_5_CCell
            cell.listItem = item.t1List
            cell.didSelectItem_Closure = { item in
                _ = item.url.openURL()
            }
            return cell
        case "t2_1":
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "T2_1_Section_CCell", for: indexPath) as! T2_1_Section_CCell
            cell.buttons = item.t2List
            return cell
        case "t3_1":
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "T3_1_Section_CCell", for: indexPath) as! T3_1_Section_CCell
            cell.brandsList = item.t3List
            return cell
        case "t3_2":
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "T3_2_CCell", for: indexPath) as! T3_2_CCell
            cell.item = item.t3List[indexPath.row]
            return cell
        case "t4_1","t4_2":
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "T4_1_Section_CCell", for: indexPath) as! T4_1_Section_CCell
            cell.productList = item.t4List
            cell.products_Cv.backgroundColor = UIColor(hex: item.bg_color)
            return cell
        case "t4_3":
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "T4_3_CCell", for: indexPath) as! T4_3_CCell
            cell.item = item.t4List[indexPath.row]
            return cell
        case "t4_4":
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "T4_4_CCell", for: indexPath) as! T4_4_CCell
            cell.item = item.t4List[indexPath.row]
            return cell
        case "t4_5":
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "T4_5_CCell", for: indexPath) as! T4_5_CCell
            cell.item = item.t4List[indexPath.row]
            cell.separate_V.isHidden = indexPath.row == item.t4List.count - 1
            return cell
        case "t4_6":
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "T4_6_CCell", for: indexPath) as! T4_6_CCell
            cell.item = item.t4List[indexPath.row]
            return cell
        case "t1_6":
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "T1_6_CCell", for: indexPath) as! T1_6_CCell
            cell.item = item
            return cell
        default:
            return UICollectionViewCell()
        }
    }
    
}
extension HomePage_Vc:UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){
        let item = self.homePageItems[indexPath.section]
        switch item.ttype { 
        case "t4_2","t4_3","t4_4","t4_5","t4_6":
            let model = item.t4List[indexPath.row]
            _ = "productdetail".openURL(["pdid":"\(model.pdid)"])
        case "t3_2":
            let model = item.t3List[indexPath.row]
            _ = "brandpage".openURL(["brid":model.internalIdentifier])
        case "t1_6":
            _ = item.headerurl.openURL()
        default:
            break
        }
    }
}
extension HomePage_Vc:SecctionBgColor_Delegate_Fl {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, backgroundColorForSectionAt section: Int) -> UIColor {
        let item = self.homePageItems[section]
        switch item.ttype {
        case "t3_2","t4_5","t4_6":
            return UIColor.white
        default:
            return UIColor.clear
        }
    }
}
extension HomePage_Vc:UICollectionViewDelegateFlowLayout{
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize{
        let item = self.homePageItems[indexPath.section]
        return item.get_cellItemSize()
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets{
        let item = self.homePageItems[section]
        return item.get_cellEdgeInsets()
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat{
        let item = self.homePageItems[section]
        return item.get_minimumLineSpacing()
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat{
        let item = self.homePageItems[section]
        return item.get_minimumInteritemSpacing()
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize{
        let item = self.homePageItems[section]
        return item.get_cellSectionHeaderSize()
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize{
        let item = self.homePageItems[section]
        return item.get_cellSectionFooterSize()
    }
}
